package com.neu.his.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.neu.his.entity.*;
import com.neu.his.entity.VO.SystemManage01.UserManage.UserQueryVO;
import com.neu.his.entity.request.UserManage.UserPageParams;
import com.neu.his.entity.request.UserManage.UserParams;
import com.neu.his.entity.request.UserManage.UserUpdateParams;
import com.neu.his.mapper.*;
import com.neu.his.service.UserService;
import com.neu.his.utils.PageList;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * Description: neu-his
 * <p>
 * Created by 31316 on 2020/7/16 21:13
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    UserRoleMapper userRoleMapper;

    @Autowired
    UserDepartmentMapper userDepartmentMapper;

    @Autowired
    DoctorMapper doctorMapper;

    @Autowired
    MedDoctorMapper medDoctorMapper;

    @Override
    public boolean insertOne(UserParams userParams) {
        if (userMapper.selectOne(new QueryWrapper<User>().eq("user_name", userParams.getUsername()).ne("remove_mark", 1)) != null)
            return false;
        User user = new User(userParams.getUsername(), userParams.getPassword(), userParams.getName());
        user.setCreateDate();
        //添加到用户表
        userMapper.insert(user);
        Long id = findUserId(user);
        //添加到用户部门表
        for (Long departmentid : userParams.getDepartment()) {
            UserDepartment userDepartment = new UserDepartment();
            userDepartment.setDepartmentId(departmentid);
            userDepartment.setUserId(id);
            userDepartmentMapper.insert(userDepartment);
        }
        //添加到用户角色表
        for (Long roleid : userParams.getUserType()) {
            UserRole userRole = new UserRole();
            userRole.setRoleId(roleid);
            userRole.setUserId(id);
            userRoleMapper.insert(userRole);
            if (roleMapper.selectById(roleid).getName().equals("医技医生")) {
                MedDoctor medDoctor = new MedDoctor(id, 30, userParams.getJobTitle());
                medDoctor.setCreateDate();
                medDoctorMapper.insert(medDoctor);
            }
            if (roleMapper.selectById(roleid).getName().equals("门诊医生")) {
                Doctor doctor = new Doctor(id, 30, userParams.getJobTitle());
                doctor.setCreateDate();
                doctorMapper.insert(doctor);
            }
        }
        return true;
    }

    @Override
    public boolean updateOne(UserUpdateParams userUpdateParams) {
        //更新用户表
        UpdateWrapper<User> updateWrapperUser = new UpdateWrapper<>();
        updateWrapperUser.set(StringUtils.isNotEmpty(userUpdateParams.getUsername()), "user_name", userUpdateParams.getUsername());
        updateWrapperUser.set(StringUtils.isNotEmpty(userUpdateParams.getPassword()), "pass_word", userUpdateParams.getPassword());
        updateWrapperUser.set(StringUtils.isNotEmpty(userUpdateParams.getName()), "name", userUpdateParams.getName());
        updateWrapperUser.set("update_date", LocalDateTime.now());
        updateWrapperUser.eq("id", userUpdateParams.getId());
        userMapper.update(null, updateWrapperUser);
        //如果部门表不为空则先删除部门表与该用户内容再添加内容
        if (userUpdateParams.getDepartment() != null && !userUpdateParams.getDepartment().isEmpty()) {
            QueryWrapper<UserDepartment> queryWrapperUD = new QueryWrapper<>();
            queryWrapperUD.eq("user_id", userUpdateParams.getId());
            userDepartmentMapper.delete(queryWrapperUD);
            for (Long departmentId : userUpdateParams.getDepartment()) {
                UserDepartment userDepartment = new UserDepartment();
                userDepartment.setUserId(userUpdateParams.getId());
                userDepartment.setDepartmentId(departmentId);
                userDepartment.setCreateDate();
                userDepartmentMapper.insert(userDepartment);
            }
        }
        //如果角色表不为空则先删除角色表，Doctor表和MedDoctor表内容，然后添加内容
        if (userUpdateParams.getUserType() != null && !userUpdateParams.getUserType().isEmpty()) {
            LambdaQueryWrapper<UserRole> queryWrapperUR = Wrappers.lambdaQuery();
            queryWrapperUR.eq(UserRole::getUserId, userUpdateParams.getId());
            userRoleMapper.delete(queryWrapperUR);
            QueryWrapper<Doctor> queryWrapperDoctor = new QueryWrapper<>();
            queryWrapperDoctor.eq("outpatient_doctor_id", userUpdateParams.getId());
            doctorMapper.delete(queryWrapperDoctor);
            QueryWrapper<MedDoctor> queryWrapperMD = new QueryWrapper<>();
            queryWrapperMD.eq("medical_doctor_id", userUpdateParams.getId());
            medDoctorMapper.delete(queryWrapperMD);
            //添加内容
            Long id = userUpdateParams.getId();
            for (Long roleid : userUpdateParams.getUserType()) {
                UserRole userRole = new UserRole();
                userRole.setRoleId(roleid);
                userRole.setUserId(id);
                userRoleMapper.insert(userRole);
                if (roleMapper.selectById(roleid).getName().equals("医技医生")) {
                    MedDoctor medDoctor = new MedDoctor(id, 30, userUpdateParams.getJobTitle());
                    medDoctor.setCreateDate();
                    medDoctorMapper.insert(medDoctor);
                }
                if (roleMapper.selectById(roleid).getName().equals("门诊医生")) {
                    Doctor doctor = new Doctor(id, 30, userUpdateParams.getJobTitle());
                    doctor.setCreateDate();
                    doctorMapper.insert(doctor);
                }
            }
        }
        return true;
    }

    @Override
    public PageList<UserQueryVO> userQuery(UserPageParams userPageParams) {
        userPageParams.init();
        //先找到符合条件的用户
        QueryWrapper<User> queryWrapperUser = new QueryWrapper<>();
        queryWrapperUser.eq(StringUtils.isNotEmpty(userPageParams.getName()), "name", userPageParams.getName());
        queryWrapperUser.eq(StringUtils.isNotEmpty(userPageParams.getPassword()), "pass_word", userPageParams.getPassword());
        queryWrapperUser.eq(StringUtils.isNotEmpty(userPageParams.getUsername()), "user_name", userPageParams.getUsername());
        queryWrapperUser.ne("remove_mark", 1L);
//        Page<User> page = new Page();
//        page.setSize(userPageParams.getPageSize());
//        page.setCurrent(userPageParams.getCurrentPage());
//        IPage<User> listUser = userMapper.selectPage(page, queryWrapperUser);
        List<UserQueryVO> list = new ArrayList<>();
        List<User> listUser = userMapper.selectList(queryWrapperUser);
        //筛选其他条件和添加其他信息
        for (User user : listUser) {
            //先筛选是否包含给出的department
            List<UserDepartment> userDepartments = userDepartmentMapper.selectList(new QueryWrapper<UserDepartment>()
                    .ne("remove_mark", 1L).eq("user_id", user.getId()));
            log.info(JSON.toJSONString(userDepartments));
            List<Long> department = new ArrayList<Long>();
            //筛选是否包含给出的role
            List<UserRole> userRoles = userRoleMapper.selectList(new QueryWrapper<UserRole>()
                    .ne("remove_mark", 1L).eq("user_id", user.getId()));
            List<Long> userType = new ArrayList<Long>();
            for (UserDepartment userDepartment : userDepartments) {
                department.add(userDepartment.getDepartmentId());
                log.info(JSON.toJSONString(userDepartment));
            }
            for (UserRole userRole : userRoles) userType.add(userRole.getRoleId());
            if (department.containsAll(userPageParams.getDepartment()) && userType.containsAll(userPageParams.getUserType())) {
                log.info("aaa");
                UserQueryVO userQueryVO = new UserQueryVO();
                userQueryVO.setId(user.getId());
                userQueryVO.setName(user.getName());
                userQueryVO.setUserName(user.getUserName());
                userQueryVO.setPassWord(user.getPassWord());
                userQueryVO.setDepartment(department);
                userQueryVO.setUserType(userType);
                Doctor doctor = doctorMapper.selectOne(new QueryWrapper<Doctor>().
                        ne("remove_mark", 1L).eq("outpatient_doctor_id", user.getId()));
                if (doctor != null) userQueryVO.setJobTitle(doctor.getDegree());
                MedDoctor medDoctor = medDoctorMapper.selectOne(new QueryWrapper<MedDoctor>().
                        ne("remove_mark", 1L).eq("medical_doctor_id", user.getId()));
                if (medDoctor != null)
                    if (userQueryVO.getJobTitle() < medDoctor.getDegree())
                        userQueryVO.setJobTitle(medDoctor.getDegree());
                log.info(JSON.toJSONString(userQueryVO));
                list.add(userQueryVO);
            }
        }
        log.info(JSON.toJSONString(list));
        int i = ((userPageParams.getCurrentPage().intValue() - 1) * userPageParams.getPageSize().intValue());

        log.info(JSON.toJSONString(i + userPageParams.getPageSize().intValue()));
        int j = i + userPageParams.getPageSize().intValue();
        List<UserQueryVO> resultlist = list.subList(i, (j < list.size() ? j : list.size()));
        log.info(JSON.toJSONString(resultlist));
        PageList<UserQueryVO> pageList = new PageList<>();
        pageList.setRecords(resultlist);
        pageList.setTotal(new Long(list.size()));
        pageList.setPageSize(userPageParams.getPageSize());
        pageList.setCurrent(userPageParams.getCurrentPage());
        log.info(JSON.toJSONString(pageList));
        return pageList;
    }

    @Override
    public List<UserQueryVO> getall() {
        List<UserQueryVO> list = new ArrayList<>();
        List<User> listUser = userMapper.selectList(new QueryWrapper<User>().ne("remove_mark", 1L));
        //筛选其他条件和添加其他信息
        for (User user : listUser) {
            List<UserDepartment> userDepartments = userDepartmentMapper.selectList(new QueryWrapper<UserDepartment>().eq("user_id", user.getId()));
            log.info(JSON.toJSONString(userDepartments));
            List<Long> department = new ArrayList<Long>();
            List<UserRole> userRoles = userRoleMapper.selectList(new QueryWrapper<UserRole>().eq("user_id", user.getId()));
            List<Long> userType = new ArrayList<Long>();
            for (UserDepartment userDepartment : userDepartments) {
                department.add(userDepartment.getDepartmentId());
                log.info(JSON.toJSONString(userDepartment));
            }
            for (UserRole userRole : userRoles) userType.add(userRole.getRoleId());
            UserQueryVO userQueryVO = new UserQueryVO();
            userQueryVO.setId(user.getId());
            userQueryVO.setName(user.getName());
            userQueryVO.setUserName(user.getUserName());
            userQueryVO.setPassWord(user.getPassWord());
            userQueryVO.setDepartment(department);
            userQueryVO.setUserType(userType);
            log.info(JSON.toJSONString(userQueryVO));
            list.add(userQueryVO);
        }
        return list;
    }

    public Long findUserId(User user) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(StringUtils.isNotEmpty(user.getUserName()), "user_name", user.getUserName());
        queryWrapper.eq(StringUtils.isNotEmpty(user.getPassWord()), "pass_word", user.getPassWord());
        queryWrapper.eq(StringUtils.isNotEmpty(user.getName()), "name", user.getName());
        queryWrapper.ne("remove_mark", 1);
        User user1 = userMapper.selectOne(queryWrapper);
        return user1.getId();
    }
}
